//
//  WayBillGuiJiVC.m
//  ReceiptDelivery
//
//  Created by 吕晶 on 2020/11/18.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "WayBillGuiJiVC.h"
#import "WayBillGuiJiModel.h"
#import "WayBillGuiJiCell.h"
#import <MapKit/MapKit.h>
#import "WayBillMapLocationModel.h"
#import "WayBillPolyline.h"
#import "LJAnnotation.h"
#import "LJAnnotationView.h"

@interface WayBillGuiJiVC ()<MKMapViewDelegate,UITableViewDelegate,UITableViewDataSource> {
    CGFloat tableViewTopMin;
    CGFloat tableViewTopMid;
    CGFloat tableViewTopMax;
}

@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) NSArray <WayBillGuiJiModel *>*array;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <NSArray *>*locationMut;

@end

@implementation WayBillGuiJiVC

-(NSMutableArray<NSArray *> *)locationMut {
    if (!_locationMut) {
        _locationMut = [NSMutableArray array];
    }
    return _locationMut;
}

-(NSArray<WayBillGuiJiModel *> *)array {
    if (!_array) {
        _array = [NSArray array];
    }
    return _array;
}

-(UIButton *)backBtn {
    if (!_backBtn) {
        _backBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, StatusBarHeight + 7, 44, 44)];
        [_backBtn setImage:[UIImage imageNamed:@"icon_map_back"] forState:0];
        [_backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

- (void)backClick {
    [self.rt_navigationController popViewControllerAnimated:YES];
}

-(MKMapView *)mapView {
    if (!_mapView) {
        _mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH)];
        _mapView.delegate = self;
    }
    return _mapView;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(15, tableViewTopMax - 1, ScreenW - 30, ScreenH - tableViewTopMin - BottomHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"img_occupy"
             titleStr:@""
            detailStr:@""];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    tableViewTopMin = 150;
    tableViewTopMax = ScreenH - 150;
    tableViewTopMid = (tableViewTopMax - tableViewTopMin) * 0.5 + tableViewTopMin;
    [self.view addSubview:self.mapView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.backBtn];
    [self requestForData];
    [self requestForMap];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (self.tableView.nim_top >= tableViewTopMid) {
        __weak_self;
        [UIView animateWithDuration:0.5 animations:^{
            __strong_self;
            weakself.tableView.nim_top = strongSelf->tableViewTopMax - 1;
        } completion:nil];
    }else {
        __weak_self;
        [UIView animateWithDuration:0.5 animations:^{
            __strong_self;
            weakself.tableView.nim_top = strongSelf->tableViewTopMin + 1;
        } completion:nil];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offSetY = scrollView.contentOffset.y;
    if (scrollView == self.tableView) {
        if (self.tableView.nim_top <= tableViewTopMin) {
            self.tableView.nim_top = tableViewTopMin;
        }else if (self.tableView.nim_top >= tableViewTopMax) {
            self.tableView.nim_top = tableViewTopMax;
        }else {
            self.tableView.nim_top -= offSetY;
        }
        NSLog(@"   %f",offSetY);
    }
}

//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
//    if (self.tableView.nim_top >= tableViewTopMid) {
//        __weak_self;
//        [UIView animateWithDuration:0.5 animations:^{
//            __strong_self;
//            weakself.tableView.nim_top = strongSelf->tableViewTopMax;
//        } completion:nil];
//    }else {
//        __weak_self;
//        [UIView animateWithDuration:0.5 animations:^{
//            __strong_self;
//            weakself.tableView.nim_top = strongSelf->tableViewTopMin;
//        } completion:nil];
//    }
//}
//
//-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    if (scrollView == self.tableView) {
//        CGFloat offSetY = scrollView.contentOffset.y;
//        if (self.tableView.nim_top < tableViewTopMin) {
//            self.tableView.nim_top = tableViewTopMin;
//        }else if (self.tableView.nim_top > tableViewTopMax) {
//            self.tableView.nim_top = tableViewTopMax;
//        }else {
////            if (self.tableView.nim_top == tableViewTopMin) {
////
////            }else {
//                self.tableView.nim_top -= offSetY;
////            }
//        }
//    }
//}

- (void)requestForMap {
    [HttpRequest PostWithApi:ReceiptDeliveryWayBillMapData params:@{@"wa_id":self.wa_id,@"type":self.type} progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            NSArray *arr = (NSArray *)responseObject;
            NSMutableArray *mm = [NSMutableArray array];
            [arr enumerateObjectsUsingBlock:^(id  _Nonnull a_obj, NSUInteger a_idx, BOOL * _Nonnull a_stop) {
                NSMutableArray *mut = [NSMutableArray array];
                [((NSArray *)a_obj) enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    [mut addObject:[WayBillMapLocationModel mj_objectWithKeyValues:obj]];
                }];
                [mm addObject:mut];
            }];
            self.locationMut = mm;
            [self configMapLine];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)configMapLine {
    if (self.locationMut.count) {
        NSMutableArray *quYuArray = [NSMutableArray array];
        [self.locationMut enumerateObjectsUsingBlock:^(NSArray * _Nonnull a_obj, NSUInteger a_idx, BOOL * _Nonnull a_stop) {
            CLLocationCoordinate2D arr[a_obj.count];
            for (int i = 0; i < a_obj.count; i ++) {
                WayBillMapLocationModel *model = a_obj[i];
                arr[i] = CLLocationCoordinate2DMake([model.lat doubleValue], [model.lng doubleValue]);
                if (i == 0) {
                    LJAnnotation *tiAn = [LJAnnotation new];
                    tiAn.coordinate = CLLocationCoordinate2DMake([model.lat doubleValue], [model.lng doubleValue]);
                    [self.mapView addAnnotation:tiAn];
                    [quYuArray addObject:tiAn];
                }
            }
            WayBillPolyline *cc = (WayBillPolyline *)[WayBillPolyline polylineWithCoordinates:arr count:a_obj.count];
            if (a_idx == 0) {
                cc.color = HexColor(0x6DD26D);
            }else if (a_idx == 1) {
                cc.color = HexColor(0xDEA543);
            }else if (a_idx == 2) {
                cc.color = HexColor(0xF68163);
            }else if (a_idx == 3) {
                cc.color = HexColor(0x6386F6);
            }else if (a_idx == 4) {
                cc.color = HexColor(0x5CE88F);
            }else if (a_idx == 5) {
                cc.color = HexColor(0xE8B55C);
            }else if (a_idx == 6) {
                cc.color = HexColor(0x427AE9);
            }else if (a_idx == 7) {
                cc.color = HexColor(0xF55555);
            }else if (a_idx == 8) {
                cc.color = HexColor(0x63ACF6);
            }else {
                cc.color = [UIColor blackColor];
            }
            [self.mapView addOverlay:cc];
        }];
        self.mapView.region = [LJAnnotation regionForAnnotations:quYuArray];
    }
}

-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
    if ([overlay isKindOfClass:[WayBillPolyline class]]) {
        //如果有MKPloylineView的overlay,将其画出
        MKPolylineRenderer *lineView = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
        lineView.strokeColor = ((WayBillPolyline *)overlay).color;
        lineView.lineWidth = 3;
        return lineView;
    }
    return nil;
}

- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
    // 自定义大头针
    if ([annotation isKindOfClass:[LJAnnotation class]]) {
        static NSString *pinID = @"LJAnnotation";
        LJAnnotationView *customPinView = (LJAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pinID];
        if (!customPinView) {
           customPinView = [[LJAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinID];
        }
        customPinView.annotation = (LJAnnotation *)annotation;
        return customPinView;
    }
    return nil;
}

- (void)requestForData {
    [HttpRequest PostWithApi:ReceiptDeliveryWayBillGuiJi params:@{@"wa_id":self.wa_id,@"type":self.type} progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.array = [WayBillGuiJiModel mj_objectArrayWithKeyValuesArray:responseObject];
            if (self.array.count) {
                self.array.firstObject.isFirst = YES;
            }
            [self.tableView reloadData];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WayBillGuiJiCell *cell = [WayBillGuiJiCell WayBillGuiJiCellWithTableView:tableView];
    if (self.array.count) {
        cell.model = self.array[indexPath.row];
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    WayBillGuiJiCell *cell = [WayBillGuiJiCell WayBillGuiJiCellWithTableView:tableView];
    if (self.array.count) {
        cell.model = self.array[indexPath.row];
    }
    return cell.height;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.array.count) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW - 30, 10)];
        view.backgroundColor = HexColor(0xffffff);
        return view;
    }
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.array.count) {
        return 10;
    }
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (self.array.count) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW - 30, 10)];
        view.backgroundColor = HexColor(0xffffff);
        return view;
    }
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (self.array.count) {
        return 10;
    }
    return 0;
}

@end
